package com.meis.base.mei.service;

import android.app.Application;

import com.meis.base.mei.entity.UserEntry;
import com.meis.base.mei.utils.ACache;

public class UserService {

    private volatile static UserService singleton = null;

    private static Application mContext;

    private static final String USER_ENTRY = "USER_ENTRY";

    private UserService() {
    }

    public static UserService getInstance() {
        testInitialize();
        if (singleton == null) {
            synchronized (UserService.class) {
                if (singleton == null) {
                    singleton = new UserService();
                }
            }
        }
        return singleton;
    }

    private static void testInitialize() {
        if (mContext == null)
            throw new ExceptionInInitializerError("请先在全局 Application 中调用 UserService.init() 初始化！");
    }

    /**
     * @param app
     */
    public static void init(Application app) {
        mContext = app;
    }

    public void saveUser(UserEntry user) {
        ACache.get(mContext).put(USER_ENTRY, user);
    }

    public void clearUser() {
        ACache.get(mContext).put(USER_ENTRY, new UserEntry());
    }

    public UserEntry getUserInfo() {
        Object userObj = ACache.get(mContext).getAsObject(USER_ENTRY);
        if (null != userObj && userObj instanceof UserEntry) {
            return (UserEntry) userObj;
        }
        return new UserEntry();
    }

    public String getToken() {
        UserEntry userInfo = getUserInfo();
        if (null != userInfo) {
            return userInfo.token;
        }
        return "";
    }
}
